package pers.zifeng.distributed.lock.common;

import lombok.extern.slf4j.Slf4j;
import pers.zifeng.distributed.lock.utils.JDBCUtils;

import java.lang.management.ManagementFactory;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author: zf
 * @date: 2021/05/14 16:49:01
 * @version: 1.0.0
 * @description: 提供mysql服务与数据库交互, 用于reids与zookepper分布式锁的业务操作
 */
@Slf4j
public class MysqlService {
    private static final String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];

    private static Connection connection;
    private static Statement statement;
    private static ResultSet resultset;

    static {
        try {
            connection = JDBCUtils.getConnection();
            statement = connection.createStatement();
            resultset = null;
        } catch (SQLException sqlException) {
            log.error("连接数据库失败！", sqlException);
        }
    }

    /**
     * 获取资源
     *
     * @param id 资源id
     * @return resultSet
     */
    public static ResultSet getGoodCount(int id) throws SQLException {
        String sql = "select * from database_lock_2 where id=" + id;
        //获取数据库连接
        resultset = statement.executeQuery(sql);
        return resultset;
    }

    /**
     * 修改资源
     *
     * @param id 资源id
     * @return 修改状态
     */
    public static boolean setGoodCount(int id, int goodCount) {
        String sql = "update database_lock_2 set good_count = good_count-1 where id=" + id + " and good_count=" + goodCount;
        try {
            //获取数据库连接
            int stat = statement.executeUpdate(sql);
            return stat == 1;
        } catch (Exception e) {
            log.error("修改库存信息失败！,e");
            return false;
        }
    }

    /**
     * 抢购一个口罩
     *
     * @return 是否抢购成功
     * @throws SQLException sql异常
     */
    public static boolean buyMask() throws SQLException {
        ResultSet resultSet = null;
        try {
            int goodCount = 0;

            log.info("【当前线程:" + pid + "】 开始购买口罩!");
            Thread.sleep(5 * 1000);
            resultSet = MysqlService.getGoodCount(1);
            while (resultSet.next()) {
                goodCount = resultSet.getInt("good_count");
            }
            if (goodCount <= 0) {
                log.info("抢购失败，当前口罩余量为0!");
                return false;
            } else {
                // 此处注意要保证数据库操作原子性，这里加上乐观锁防止数据越界问题
                if (MysqlService.setGoodCount(1, goodCount)) {
                    log.info("【当前线程:" + pid + "】 抢购商品成功，剩余库存为：" + --goodCount);
                } else {
                    log.error("【当前线程:" + pid + "】 抢购商品失败，商品数量已被修改!");
                }
            }
            Thread.sleep(5 * 1000);
            return true;
        } catch (Exception e) {
            log.error("抢购口罩失败！", e);
            return false;
        } finally {
            if (resultSet != null) {
                resultSet.close();
            }
        }
    }

    public static void close() {
        log.info("当前线程:" + ManagementFactory.getRuntimeMXBean().getName().split("@")[0] + ",关闭了数据库连接！");
        JDBCUtils.close(resultset, statement, connection);
    }

}
